const express = require("express");
const NotificationService = require("../services/notificationService");
const auth = require("../middleware/auth");

const router = express.Router();

// 获取用户通知列表
router.get("/", auth, async (req, res) => {
  try {
    const { page = 1, limit = 20, unreadOnly = false } = req.query;

    const result = await NotificationService.getUserNotifications(
      req.user.id,
      Number(page),
      Number(limit),
      unreadOnly === "true"
    );

    return res.status(200).json(result);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 获取未读通知数量
router.get("/unread-count", auth, async (req, res) => {
  try {
    const count = await NotificationService.getUnreadCount(req.user.id);
    return res.status(200).json({ count });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 标记单个通知为已读
router.patch("/:notificationId/read", auth, async (req, res) => {
  try {
    const { notificationId } = req.params;

    const notification = await NotificationService.markAsRead(
      notificationId,
      req.user.id
    );

    if (!notification) {
      return res.status(404).json({ message: "通知不存在或已标记为已读" });
    }

    return res.status(200).json({ message: "通知已标记为已读" });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 标记所有通知为已读
router.patch("/mark-all-read", auth, async (req, res) => {
  try {
    const count = await NotificationService.markAllAsRead(req.user.id);
    return res.status(200).json({
      message: "所有通知已标记为已读",
      count,
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

module.exports = router;
